/*

	Hernan Rivas Acosta
		hernanrivasacosta@gmail.com

	Licenced under the Mozilla Public Licence
		http://www.mozilla.org/MPL/MPL-1.1.html

	Hosted on Google Code
		http://code.google.com/p/as3localization/

*/
package org.her.localization.utils
{
	import flash.utils.Dictionary;

	public class StringUtils
	{

		/**
		 * Returns a string where all the values between braces are replaced with the values in the replaceObj. If the value in the replaceObj is a Function, it will be called with no arguments.
		 *
		 * @param str The string where to find the replaceable strings.
		 * @param replaceObj A dictionary or an Array where the replaceable values are stored. If the value is an Array, all values between curly braces will be casted to integers.
		 *
		 * @example The following code outputs "Created by Hernan Rivas" 3 times:
		 * <listing version="3.0">
		 * var dic:Dictionary;
		 * dic['name'] = 'Hernan';
		 * dic['lastName'] = 'Rivas';
		 *
		 * var arr:Array;
		 * arr = new Array ('Hernan', 'Rivas');
		 *
		 * trace (findAndReplace ('Created by {name} {lastName}', dic));
		 * trace (findAndReplace ('Created by {0} {1}', arr));
		 * trace (findAndReplace ('Created by {0} {1}', ['Hernan', 'Rivas']));
		 * </listing>
		 *
		 * @return A new string where all possible values were replaced.
		 */
		public static function findAndReplace (str:String, replaceObj:*):String
		{
			if (replaceObj is Array)
			{
				return str.replace(/{([\S]+)}/g, getArrayReplaceFunction(replaceObj));
			}
			else if (replaceObj is Dictionary)
			{
				return str.replace(/{([\S]+)}/g, getDictionaryReplaceFunction(replaceObj));
			}
			else
			{
				throw new Error ('WARNING: StringUtils.findAndReplace failed. Reason: replaceObj should be an Array or a Dictionary.');
				return null;
			}
		}

		private static function getDictionaryReplaceFunction (dic:Dictionary):Function
		{
			return	function (...args):String
					{
						var value:*;

						value = dic[parseInt(args[1])];

						if (value != null)
						{
							return value is Function? value().toString() : value.toString();
						}
						else
						{
							return args[0];
						}
					}
		}

		private static function getArrayReplaceFunction (arr:Array):Function
		{
			return	function (...args):String
					{
						var value:*;

						value = arr[args[1]];

						if (value != null)
						{
							return value is Function? value().toString() : value.toString();
						}
						else
						{
							return args[0];
						}
					}
		}

	}
}